class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def isSubPath(self, head, root):
        self.flag = False

        def dfs(node, p_list):
            next_list = []
            for p in p_list:
                if p.val == node.val:
                    np = p.next
                    if np:
                        next_list.append(np)
                    else:
                        self.flag = True
            next_list.append(head)
            if not self.flag:
                if node.left:
                    dfs(node.left, next_list)
                if node.right:
                    dfs(node.right, next_list)

        dfs(root, [head])
        return self.flag

